<template>
  <div class="apply-settlement">
    <el-drawer v-model="showDialog" direction="rtl" :show-close="false" size="550px">
      <template #header>
        <div class="header">
          <custom-title title="生成结算单" />
        </div>
      </template>
      <div v-loading="detailLoading">
        <!--    start step-list-->
        <div class="step-list">
          <div class="step-item" :class="{ 'step-item--active': currentStep === 0, 'step-item--complete': currentStep === 1 }">
            <span v-if="currentStep === 0">1</span
            ><span v-else
              ><el-icon size="12" color="#007DFF"><Select /></el-icon></span
            >验证单据是否完成
          </div>
          <div class="step-line"></div>
          <div class="step-item" :class="{ 'step-item--active': currentStep === 1 }"><span>2</span>确认金额</div>
        </div>
        <!--    end step-list-->
        <!--    start step-content-->
        <div class="step-content">
          <div class="total-list">
            <div class="total-list__row">
              <div class="money-detail">
                <div class="label">发包总金额:</div>
                <div class="value">￥{{ detailInfo.contracteesAmount }}</div>
              </div>
              <div class="money-detail" style="justify-content: flex-end">
                <div class="label">剩余发包总金额:</div>
                <div class="value">￥{{ detailInfo.remainingContractAmount }}</div>
              </div>
            </div>
            <div class="total-list__row">
              <div class="money-detail">
                <div class="label">非发包已请款总金额:</div>
                <div class="value">￥{{ detailInfo.receivedLaborAmount }}</div>
              </div>
            </div>
          </div>
          <div class="bill-list" v-if="currentStep === 0">
            <div class="bill-item" v-for="item in documentsList">
              <div class="flex-row">
                <div class="bill-item__name" :style="{ color: item.isLoading ? '#86909C' : '#3D3D3D' }">
                  <img src="@/assets/images/settleManage/triangle-icon.png" />
                  {{ item.text }}
                </div>
                <div class="bill-item__line"></div>
              </div>

              <div class="bill-item__status">
                <template v-if="item.isLoading">
                  <img src="@/assets/images/settleManage/ing-icon.png" />
                </template>
                <template v-else>
                  <img v-if="item.isPass" src="@/assets/images/settleManage/correct-icon.png" />
                  <img v-else src="@/assets/images/settleManage/error-icon.png" />
                </template>
              </div>
            </div>
          </div>
          <div class="partner-list" v-if="currentStep === 1">
            <div class="sub-title">合作方质保金</div>
            <div class="form-content">
              <div class="form-item" v-for="(item, index) in retentionMoneyForm">
                <el-select-v2
                  v-model="item.partnerId"
                  filterable
                  remote
                  :remote-method="query => remoteMethodPartner(query, index, 'retentionMoney')"
                  clearable
                  :options="item.partnerOptions"
                  :props="{ label: 'optionName', value: 'partnerId' }"
                  placeholder="请输入合作方名称"
                  @change="partnerChange($event, index, 'retentionMoney')"
                  style="flex: 1"
                />
                <el-input v-model.trim="item.money" style="flex: 1" placeholder="请输入金额" type="number">
                  <template #suffix>￥</template>
                </el-input>
              </div>
              <div class="add-item" @click="addPartner('retentionMoney')">
                <el-icon color="#007DFF" size="14"><CirclePlusFilled /></el-icon>
                <span>添加合作方</span>
              </div>
            </div>
            <div class="sub-title">合作方押金</div>
            <div class="form-content">
              <div class="form-item" v-for="(item, index) in depositForm">
                <el-select-v2
                  v-model="item.partnerId"
                  filterable
                  remote
                  :remote-method="query => remoteMethodPartner(query, index, 'deposit')"
                  clearable
                  :options="item.partnerOptions"
                  :props="{ label: 'optionName', value: 'partnerId' }"
                  placeholder="请输入合作方名称"
                  @change="partnerChange($event, index, 'deposit')"
                  style="flex: 1"
                />
                <el-input v-model.trim="item.money" style="flex: 1" placeholder="请输入金额" type="number">
                  <template #suffix>￥</template>
                </el-input>
              </div>
              <div class="add-item" @click="addPartner('deposit')">
                <el-icon color="#007DFF" size="14"><CirclePlusFilled /></el-icon>
                <span>添加合作方</span>
              </div>
            </div>
          </div>
        </div>
        <!--    end step-content-->
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="handleCancel" size="default">取消 </el-button>
          <el-button
            style="width: 92px"
            type="primary"
            :disabled="disabledNextStep"
            v-if="currentStep === 0"
            size="default"
            @click="currentStep = 1"
            >下一步</el-button
          >
          <el-button v-if="currentStep === 1" style="width: 92px" type="primary" @click="handleConfirm" size="default"
            >确定</el-button
          >
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { computed, ref, getCurrentInstance, reactive } from "vue";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import {
  settlementDetails,
  havePleaseSlip,
  hasMaterialSlip,
  hasDutySlip,
  hasReimburseSlip,
  getPartner,
  submitApplySettlement
} from "@/apis/settlementManagement";
import { type } from "@/utils/config";
import { accAdd } from "@/utils";

const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  contractId: {
    type: String,
    default: ""
  }
});

const contractId = props.contractId;
const showDialog = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const emit = defineEmits(["update:modelValue", "handleApplySave"]);

//step
const currentStep = ref(0);

//合作方质保金/押金
const retentionMoneyForm = ref([]);
const depositForm = ref([]);
const addPartner = type => {
  if (type === "retentionMoney") {
    retentionMoneyForm.value.push({
      partnerId: "",
      money: "",
      partnerName: "",
      serviceType: "1",
      partnerOptions: []
    });
  }
  if (type === "deposit") {
    depositForm.value.push({
      partnerId: "",
      money: "",
      partnerName: "",
      serviceType: "2",
      partnerOptions: []
    });
  }
};

const partnerChange = (val, index, type) => {
  if (type === "retentionMoney") {
    const filterItem = retentionMoneyForm.value[index].partnerOptions.find(item => item.partnerId === val);
    if (!filterItem) return;
    retentionMoneyForm.value[index].partnerName = filterItem.name;
  } else {
    const filterItem = depositForm.value[index].partnerOptions.find(item => item.partnerId === val);
    if (!filterItem) return;
    depositForm.value[index].partnerName = filterItem.name;
  }
};
const remoteMethodPartner = async (value, index, payType) => {
  if (value.trim() == "") {
    if (payType === "retentionMoney") {
      retentionMoneyForm.value[index].partnerOptions = [];
    } else {
      depositForm.value[index].partnerOptions = [];
    }
    return;
  }
  const { data } = await getPartner(value || undefined);
  if (payType === "retentionMoney") {
    retentionMoneyForm.value[index].partnerOptions = data?.map(v => ({ ...v, optionName: type[v.type] + " : " + v.name }));
  } else {
    depositForm.value[index].partnerOptions = data?.map(v => ({ ...v, optionName: type[v.type] + " : " + v.name }));
  }
};

//按钮操作
const handleCancel = () => {
  showDialog.value = false;
};
const handleConfirm = async () => {
  //金额校验
  const detailList = [...retentionMoneyForm.value, ...depositForm.value];
  const isPassRuleMoney = detailList?.every(item => {
    return /^\d{1,10}(\.\d{1,2})?$/.test(item.money);
  });
  if (!isPassRuleMoney) {
    return proxy.$modal.msgWarning("金额不能为空，且仅限10位数字，小数点后两位");
  }
  const moneyTotal = detailList?.reduce((accumulator, currentValue) => {
    return accAdd(accumulator, Number(currentValue.money));
  }, 0);
  if (Number(detailInfo.value.contracteesAmount > 0)) {
    if (moneyTotal > Number(detailInfo.value.remainingContractAmount)) {
      return proxy.$modal.msgWarning("押金和质保金之和不可大于剩余发包金额");
    }
  }
  await submitApplySettlement({
    contractId,
    detailList
  });
  proxy.$modal.msgSuccess("结算申请成功");
  showDialog.value = false;
  emit("handleApplySave");
};

//详情
const detailInfo = ref({});
const detailLoading = ref(false);
const documentsList = reactive([
  { text: "请款单全部审批通过", isPass: false, isLoading: true },
  { text: "领料单全部审批通过", isPass: false, isLoading: true },
  { text: "判责单全部核实", isPass: false, isLoading: true },
  { text: "报销单全部审批通过", isPass: false, isLoading: true }
]);
const getDetail = async () => {
  detailLoading.value = true;
  const { data } = await settlementDetails(contractId);
  detailInfo.value = data ?? {};
  detailLoading.value = false;
};
const getDocumentsList = () => {
  havePleaseSlip(contractId).then(res => {
    documentsList[0].isPass = res.data ?? false;
    documentsList[0].isLoading = false;
  });
  hasMaterialSlip(contractId).then(res => {
    documentsList[1].isPass = res.data ?? false;
    documentsList[1].isLoading = false;
  });
  hasDutySlip(contractId).then(res => {
    documentsList[2].isPass = res.data ?? false;
    documentsList[2].isLoading = false;
  });
  hasReimburseSlip(contractId).then(res => {
    documentsList[3].isPass = res.data ?? false;
    documentsList[3].isLoading = false;
  });
};
const disabledNextStep = computed(() => {
  const filterErrorData = documentsList.find(item => !item.isLoading && !item.isPass);
  return filterErrorData ? true : false;
});

getDetail();
getDocumentsList();
</script>
<style lang="scss" scoped>
@import "@/assets/styles/index.scss";
.apply-settlement {
  :deep(.el-drawer__header) {
    margin-bottom: 25px;
  }
  :deep(.el-drawer__body) {
    padding-top: 0;
  }
  :deep(.el-drawer__footer) {
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding-top: 12px;
    padding-bottom: 12px;
  }
}

//step-list
.step-list {
  @include flexStyle();

  .step-line {
    width: calc(100% - 300px);
    border: 1px dashed #d8d8d8;
  }

  .step-item {
    @include flexStyle(flex-start, center);
    font-size: 16px;
    span {
      @include blockStyle(28px, 28px, #f2f3f5, 14px);
      @include flexStyle(center, center);
      @include fontStyle(16px, #4e5969);
      margin-right: 10px;
    }

    &--active {
      color: #1d2129;

      span {
        background-color: #165dff;
        color: #fff;
      }
    }

    &--complete {
      color: #1d2129;

      span {
        background-color: #e8f3ff;
      }
    }
  }
}

//total-list
//.total-list {
//  @include flexStyle();
//  margin-top: 30px;
//  gap: 10px;
//
//  &__row {
//    flex: 1;
//    background: #f5f7fa;
//    border-radius: 4px;
//    @include flexStyle(center, center);
//
//    .money-detail {
//      flex: 1;
//      text-align: center;
//      padding: 20px 15px;
//      font-size: 14px;
//
//      .label {
//        color: #4e5969;
//        margin-bottom: 10px;
//        white-space: nowrap;
//      }
//
//      .value {
//        color: #1a1a1a;
//      }
//    }
//  }
//}
//total-list
.total-list {
  background: #f5f7fa;
  border-radius: 4px;
  margin-top: 30px;
  margin-bottom: 20px;
  padding: 15px;
  &__row {
    background: #fff;
    margin-bottom: 15px;
    height: 36px;
    padding-right: 15px;
    border-radius: 4px;
    @include flexStyle();
    overflow: hidden;
    &:last-child {
      margin-bottom: 0;
    }
    &::before {
      content: "";
      @include blockStyle(2px, 36px, #007dff, 4px);
      display: inline-block;
      margin-right: 10px;
    }
    .money-detail {
      @include flexStyle(flex-start, center);
      flex: 1;
      .label {
        @include fontStyle(14px, #4e5969);
      }
      .value {
        @include fontStyle(14px, #1a1a1a);
      }
    }
  }
}
//step-content
.step-content {
  .bill-list {
    .bill-item {
      @include flexStyle(space-between, center);
      margin-bottom: 10px;

      .flex-row {
        @include flexStyle(flex-start, center);
        flex-grow: 1;
      }

      &__name {
        @include flexStyle(flex-start, center);
        flex-shrink: 0;
        font-size: 14px;
        img {
          width: 10px;
          margin-right: 15px;
        }
      }

      &__line {
        border-bottom: 1px dashed #d8d8d8;
        flex-grow: 1;
        margin: 0 15px;
      }

      &__status {
        img {
          width: 20px;
        }
      }
    }
  }

  .partner-list {
    .sub-title {
      @include fontStyle(14px, #3d3d3d);
      margin-bottom: 10px;
    }

    .form-content {
      margin-bottom: 20px;

      .form-item {
        @include flexStyle(space-between, center);
        gap: 5px;
        margin-bottom: 10px;
      }

      .add-item {
        border: 1px solid #dcdfe6;
        width: 100%;
        padding: 7px 15px;
        box-sizing: border-box;
        @include flexStyle(flex-start, center);
        @include fontStyle(12px, #007dff);
        cursor: pointer;

        span {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
